/*
 * @(#)LogInOutController.java $version 2012. 5. 18.
 *
 */

package com.mywep.myalimi.controller;

import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.mywep.myalimi.constant.LogInOut;
import com.mywep.myalimi.model.User;
import com.mywep.myalimi.service.UserService;

/**
 * @author 한지웅
 */
@Controller
@RequestMapping("/alimiLogin")
public class LogInOutController {
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/logPage.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView logPage() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("logPage");
		return mav;
	}
	
	@RequestMapping(value = "/login.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView logIn(HttpSession session, String id, String passwd) {
		ModelAndView mav = new ModelAndView();

		User userKey = new User();
		userKey.setId(id);
		User user = userService.getUserInfo(userKey);
		if (user != null && StringUtils.equals(user.getPasswd(), passwd)) {
			session.setAttribute(LogInOut.SESSIONUSERID.getName(), user.getId());
			session.setMaxInactiveInterval(600);
			mav.setViewName(String.format("redirect:%s", "/alimi/keyword/get.alm"));
		} else {
			mav.setViewName("logPage");
		}

		return mav;
	}

	@RequestMapping(value = "/logout.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView logOut(HttpSession session) {
		ModelAndView mav = new ModelAndView();
		session.setAttribute(LogInOut.SESSIONUSERID.getName(), null);
		mav.setViewName("logPage");
		return mav;
	}

	@RequestMapping(value = "/join.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView joinPage(HttpSession session, String id, String passwd) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("join");
		return mav;
	}

	@RequestMapping(value = "/addUser.alm", method = {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView addUser(HttpSession session, String id, String passwd) {
		ModelAndView mav = new ModelAndView();

		User user = new User();
		user.setId(id);
		user.setPasswd(passwd);
		try {
			KeyGenerator.getInstance("AES");
		} catch (NoSuchAlgorithmException e) {
		}

		userService.txAddUser(user);

		session.setAttribute(LogInOut.SESSIONUSERID.getName(), user.getId());
		session.setMaxInactiveInterval(600);
		mav.setViewName(String.format("redirect:%s", "/alimi/keyword/get.alm"));

		return mav;
	}


}
